<template>
  <div class="problem-ticket-page">
    <!-- 查询表单 -->
    <el-card class="query-card" shadow="never">
      <el-form :model="queryForm" inline>
        <el-form-item label="工单标题">
          <el-input
            v-model="queryForm.title"
            placeholder="请输入工单标题"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="问题类型">
          <el-select
            v-model="queryForm.type"
            placeholder="请选择问题类型"
            clearable
            style="width: 150px"
          >
            <el-option label="设备故障" value="equipment-fault" />
            <el-option label="系统异常" value="system-error" />
            <el-option label="数据异常" value="data-error" />
            <el-option label="网络问题" value="network-issue" />
            <el-option label="其他问题" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="工单状态">
          <el-select
            v-model="queryForm.status"
            placeholder="请选择工单状态"
            clearable
            style="width: 120px"
          >
            <el-option label="待处理" value="pending" />
            <el-option label="处理中" value="processing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已关闭" value="closed" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建日期">
          <el-date-picker
            v-model="queryForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="operation-card" shadow="never">
      <el-button type="primary" @click="handleAdd">新增工单</el-button>
      <el-button
        type="danger"
        :disabled="!selectedRows.length"
        @click="handleBatchDelete"
      >
        批量删除
      </el-button>
      <el-button type="success" @click="handleExport">导出数据</el-button>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        stripe
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="ticketNo" label="工单编号" width="120" />
        <el-table-column prop="title" label="工单标题" width="200" />
        <el-table-column prop="type" label="问题类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityTagType(row.priority)">
              {{ getPriorityText(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reporter" label="报告人" width="100" />
        <el-table-column prop="assignee" label="处理人" width="100" />
        <el-table-column prop="status" label="工单状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="updateTime" label="更新时间"  />
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" icon="Edit" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="primary" icon="View" @click="handleView(row)">查看</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 表单弹窗 -->
    <ProblemTicketFormDialog
      v-model:visible="dialogVisible"
      :form-data="currentRow"
      :is-view="isView"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import ProblemTicketFormDialog from './components/ProblemTicketFormDialog.vue'

// 查询表单
const queryForm = reactive({
  title: '',
  type: '',
  status: '',
  dateRange: []
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])
const allData = ref([] as any[])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 弹窗相关
const dialogVisible = ref(false)
const currentRow = ref(null)
const isView = ref(false)

// 获取类型标签样式
const getTypeTagType = (type: string) => {
  const typeMap = {
    'equipment-fault': 'danger',
    'system-error': 'warning',
    'data-error': 'info',
    'network-issue': 'primary',
    'other': 'success'
  }
  return typeMap[type] || 'info'
}

// 获取类型文本
const getTypeText = (type: string) => {
  const typeMap = {
    'equipment-fault': '设备故障',
    'system-error': '系统异常',
    'data-error': '数据异常',
    'network-issue': '网络问题',
    'other': '其他问题'
  }
  return typeMap[type] || type
}

// 获取优先级标签样式
const getPriorityTagType = (priority: string) => {
  const priorityMap = {
    high: 'danger',
    medium: 'warning',
    low: 'success'
  }
  return priorityMap[priority] || 'info'
}

// 获取优先级文本
const getPriorityText = (priority: string) => {
  const priorityMap = {
    high: '高',
    medium: '中',
    low: '低'
  }
  return priorityMap[priority] || priority
}

// 获取状态标签样式
const getStatusTagType = (status: string) => {
  const statusMap = {
    pending: 'warning',
    processing: 'primary',
    completed: 'success',
    closed: 'info'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    pending: '待处理',
    processing: '处理中',
    completed: '已完成',
    closed: '已关闭'
  }
  return statusMap[status] || status
}

// 生成伪数据
const randomChoice = (arr: any[]) => arr[Math.floor(Math.random() * arr.length)]
const generateMockData = (count: number) => {
  const types = ['equipment-fault', 'system-error', 'data-error', 'network-issue', 'other']
  const priorities = ['high', 'medium', 'low']
  const statuses = ['pending', 'processing', 'completed', 'closed']
  const names = ['张三', '李四', '王五', '赵六', '钱七']
  const departments = ['运维部', '监测中心', '信息中心']
  const list = [] as any[]
  for (let i = 0; i < count; i++) {
    const id = i + 1
    const type = randomChoice(types)
    const priority = randomChoice(priorities)
    const status = randomChoice(statuses)
    const reporter = randomChoice(names)
    const assignee = randomChoice(names)
    const dept = randomChoice(departments)
    const date = new Date(2024, Math.floor(Math.random() * 6) + 1, Math.floor(Math.random() * 28) + 1)
    const createAt = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(Math.floor(Math.random()*24)).padStart(2,'0')}:${String(Math.floor(Math.random()*60)).padStart(2,'0')}:00`
    const updateAt = createAt
    list.push({
      id,
      ticketNo: `PT2024${String(id).padStart(3, '0')}`,
      title: `${getTypeText(type)}问题-${id}`,
      type,
      priority,
      reporter,
      assignee,
      status,
      createTime: createAt,
      updateTime: updateAt,
      phone: '13800138000',
      email: 'demo@example.com',
      department: dept,
      description: '示例问题描述',
      solution: '示例处理方案',
      result: status === 'completed' ? '已处理完成' : '处理中',
      remark: '示例备注'
    })
  }
  return list
}

// 根据查询与分页应用数据
const applyFiltersAndPaginate = () => {
  const { title, type, status } = queryForm
  const filtered = allData.value.filter((item) => {
    const matchTitle = title ? item.title.includes(title) : true
    const matchType = type ? item.type === type : true
    const matchStatus = status ? item.status === status : true
    return matchTitle && matchType && matchStatus
  })
  pagination.total = filtered.length
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  tableData.value = filtered.slice(start, end)
}

// 模拟API - 获取问题工单列表
const fetchProblemTicketList = async () => {
  loading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 300))
    const count = Math.floor(Math.random() * 41) + 10
    allData.value = generateMockData(count)
    applyFiltersAndPaginate()
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 模拟API - 删除问题工单
const deleteProblemTicket = async (ids: number[]) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 200))
    allData.value = allData.value.filter(item => !ids.includes(item.id))
    applyFiltersAndPaginate()
    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 查询
const handleQuery = () => {
  pagination.currentPage = 1
  applyFiltersAndPaginate()
}

// 重置
const handleReset = () => {
  Object.assign(queryForm, {
    title: '',
    type: '',
    status: '',
    dateRange: []
  })
  pagination.currentPage = 1
  applyFiltersAndPaginate()
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  applyFiltersAndPaginate()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  applyFiltersAndPaginate()
}

// 弹窗成功回调
const handleDialogSuccess = () => {
  fetchProblemTicketList()
}

// 初始化
onMounted(() => {
  fetchProblemTicketList()
})
</script>

<style scoped>
.problem-ticket-page {
  padding: 20px;
}

.query-card,
.operation-card,
.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>